package com.fitz.core.filter;

import com.fitz.core.context.RequestContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gousl01
 * @date 2021/3/15 14:20
 * @desc
 */
public class GatewayBaseFilter implements Filter {

    private FitzRunner fitzRunner;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        fitzRunner = new FitzRunner();
    }

    /**
     * 拦截请求以后开始处理 pre、route、post
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        fitzRunner.init((HttpServletRequest) servletRequest,(HttpServletResponse) servletResponse);
        try {
            fitzRunner.preRoute();
            fitzRunner.route();
            fitzRunner.postRoute();
        } catch (Throwable throwable) {
            RequestContext.getCurrentContext().setThrowable(throwable);
            fitzRunner.errorRoute();
        }

    }

    @Override
    public void destroy() {

    }
}
